/*
 * Copyright (C) 2012 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package com.example.google.tv.picasanotifier;

import android.database.Cursor;
import android.util.Log;

import com.example.google.tv.picasanotifier.model.AlbumData;
import com.example.google.tv.picasanotifier.model.AlbumEntry;
import com.example.google.tv.picasanotifier.model.PhotoData;
import com.example.google.tv.picasanotifier.model.PhotoEntry;
import com.example.google.tv.picasanotifier.model.PicasaUrl;
import com.example.google.tv.picasanotifier.model.UserFeed;
import com.google.api.client.apache.ApacheHttpTransport;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.xml.atom.AtomParser;
import com.google.api.data.picasa.v2.PicasaWebAlbums;
import com.google.api.data.picasa.v2.atom.PicasaWebAlbumsAtom;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Utility class to interact with the Picasa Atom API This class is used as a
 * singleton and cannot be instantiated. Instead, you must use {@link #get()} to
 * retrieve the unique instance of this class.
 */
class Picasa {
    
    private static final String TAG = "Picasa";

    public static final String API_FEED_URL = "feed/api/user/";

    private static final Picasa INSTANCE = new Picasa();

    private static final GoogleTransport TRANSPORT = new GoogleTransport();

    public static int mPhotoPos = 0;

    List<PhotoEntry> mPhotoEntries;

    PhotoData mData;

    ArrayList<AlbumData> mAlbumData = new ArrayList<AlbumData>();

    ArrayList<PhotoData> mPhotoData = new ArrayList<PhotoData>();

    Cursor mCursor;

    UserDatabase mUserDb;

    /**
     * Returns the unique instance of this class.
     * 
     * @return The unique instance of this class.
     */
    static Picasa get() {
        return INSTANCE;
    }

    HttpTransport picasaInit() {
        TRANSPORT.applicationName = "google-picasawbalbum-1.0";
        HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
        TRANSPORT.setVersionHeader(PicasaWebAlbums.VERSION);
        AtomParser parser = new AtomParser();
        parser.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY;
        TRANSPORT.addParser(parser);
        return TRANSPORT;
    }

    /**
     * Retrieves a list of albums for the specified user.
     * 
     * @param username The user to retrieve albums from.
     * @return The list of albums
     */
    public List<AlbumEntry> getUserAlbums(String username) {
        final Picasa mPicasa = Picasa.get();
        HttpTransport transport = mPicasa.picasaInit();
        List<AlbumEntry> mAlbumEntry = new ArrayList<AlbumEntry>();
        mAlbumEntry.clear();
        try {
            PicasaUrl url = PicasaUrl.fromRelativePath(Picasa.API_FEED_URL + username);
            while (true) {
                UserFeed userFeed = UserFeed.executeGet(transport, url);
                if (userFeed.mAlbums != null) {
                    mAlbumEntry.addAll(userFeed.mAlbums);
                }
                String nextLink = userFeed.getNextLink();
                if (nextLink == null) {
                    break;
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Couldn't obtain the albums");
            mAlbumEntry.clear();
        }
        return mAlbumEntry;
    }

    /**
     * Checks the specified user's feed to see if any updated occurred after the
     * specified date
     * 
     * @param username The user whose feed must be checked
     * @param reference The date after which to check for updates.
     * @return True if any update occurred after the reference date, false
     *         otherwise.
     */
    public boolean hasUpdates(String username, final Calendar reference) {
        picasaInit();
        List<AlbumEntry> mAlbums = getUserAlbums(username);
        final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < mAlbums.size(); i++) {
            final Calendar calendar = new GregorianCalendar();
            final String text = mAlbums.get(i).updated.replace('T', ' ').replace('Z', ' ');
            try {

                calendar.setTimeInMillis(format.parse(text).getTime());

            } catch (ParseException e) {
                Log.e(TAG, "Couldn't parse the text");
            }
            if (reference.after(calendar)) {
                return true;
            }
        }
        return false;
    }
}
